package com.colaiven.hbastest.controller;

import com.colaiven.hbastest.utils.HBaseUtil;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.util.Bytes;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/truck")
public class TruckController {
    @RequestMapping("/getTruck")
    public List<Map<String,String>> getTruck(String terminalNo,String startTime,String endTime) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String rowKeyStart = Long.parseLong(terminalNo) % 100+"_"+terminalNo+"_"+sdf.parse(startTime).getTime();
        String rowKeyEnd = Long.parseLong(terminalNo) % 100+"_"+terminalNo+"_"+sdf.parse(endTime).getTime();
        ResultScanner results = HBaseUtil.scanByRowKey("colaiven", rowKeyStart, rowKeyEnd);
        List<Map<String,String>> trucks = new LinkedList<>();
        for (Result result : results) {
            Map<String,String> truck = new LinkedHashMap<>();
            String rowKey = Bytes.toString(result.getRow());
            truck.put("time",sdf.format(new Date(Long.parseLong(rowKey.substring(rowKey.lastIndexOf("_")+1)))));
            Cell[] cells = result.rawCells();
            for (Cell cell: cells) {
                truck.put(Bytes.toString(CellUtil.cloneQualifier(cell)),Bytes.toString(CellUtil.cloneValue(cell)));
            }
            trucks.add(truck);
        }
        return trucks;
    }
}
